import QRCode from 'qrcode'
/**
 *
 * @param value 需要copy的字符串
 * @returns
 */
export function copyText(value: string) {
  return new Promise((resolve) => {
    const input = document.createElement('textarea')
    input.value = value
    document.body.appendChild(input)
    input.select()
    document.execCommand('Copy')
    document.body.removeChild(input)
    resolve(true)
  })
}

/**
 *
 * @param evtobj 事件对象
 * @param fn  回掉函数
 */
export function ctrlAddZ(evtobj: { keyCode: number; ctrlKey: any }, fn: () => void) {
  if (evtobj.keyCode == 90 && evtobj.ctrlKey) fn()
}

/**
 * qrcode download
 */
export function downloadQrcodeFromUrl(url: string, name: string) {
  const canvas = document.createElement('canvas')
  QRCode.toCanvas(
    canvas,
    url,
    {
      width: 250,
      color: {
        dark: '#000000',
        light: '#ffffff',
      },
    },
    (error: any) => {
      if (error) throw error
    },
  )
  const imageUrl = canvas.toDataURL('image/png')
  const a = document.createElement('a')
  a.download = name
  a.href = imageUrl
  a.dataset.downloadurl = ['image/png', name, imageUrl].join(':')
  a.click()
}

export const isWechat = () => {
  //获取user-agaent标识头
  const ua = window.navigator.userAgent.toLowerCase()
  //判断ua和微信浏览器的标识头是否匹配
  if (ua.match(/micromessenger/i) == 'micromessenger') {
    return true
  } else {
    return false
  }
}
export const isZhiyinlou = () => {
  //获取user-agaent标识头
  const ua = window.navigator.userAgent.toLowerCase()
  //判断ua和微信浏览器的标识头是否匹配
  if (ua.match(/yach/i) == 'yach') {
    return true
  } else {
    return false
  }
}

const UA = window.navigator.userAgent

export const deviceDecide = {
  UA,
  isXKApp: (): boolean => /subject_jzh/.test(UA), // 是否是希望学app
  isWechat: (): boolean => /micromessenger/i.test(UA) && !/miniprogram/i.test(UA),
  isWechatProgram: (): boolean => /miniprogram/i.test(UA),
  isZhiyinlou: (): boolean => /yach/i.test(UA),
  isQQ: (): boolean => /\sQQ\/\d/.test(UA),
  isAndroid: (): boolean => /android/i.test(UA),
  isIphone: (): boolean => /iphone/gi.test(UA),
  isIphoneX: (): boolean => {
    const { height, width } = window.screen
    return (
      /iphone/gi.test(UA) &&
      ((height === 812 && width === 375) ||
        (height === 896 && width === 414) ||
        (height === 926 && width === 428))
    )
  },
  isIpad: (): boolean => /iPad/gi.test(UA),
}
